package base

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"gorm.io/gorm"
	"hosptial-record/global"
	"hosptial-record/global/response"
	"net/http"
	"strconv"
	"strings"
)

// GetID2Param 获取param中的ID
func GetID2Param(ctx *gin.Context) (id int32, err error) {
	str := ctx.Param("id")
	var i int
	i, err = strconv.Atoi(str)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, response.BaseResponse{
			Msg: "传入的ID不合法",
		})
		return id, err
	}
	id = int32(i)
	return id, err
}
func RemoveTopStruct(fields map[string]string) map[string]string {
	rsp := map[string]string{}
	for field, err := range fields {
		key := strings.Split(field, ".")[1]
		rsp[key] = err
	}
	return rsp
}

func HandleValidatorError(ctx *gin.Context, err error) {
	var errs validator.ValidationErrors
	ok := errors.As(err, &errs)
	if !ok {
		ctx.JSON(http.StatusBadRequest, response.BaseResponse{
			Msg: err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusBadRequest, gin.H{
		"error": RemoveTopStruct(errs.Translate(global.Trans)),
	})
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page == 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}
		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
